package com.dong.algorithm.novice.introduction;

import com.dong.algorithm.novice.sort.BubbleSort;
import com.dong.algorithm.novice.sort.InsertionSort;
import com.dong.algorithm.novice.sort.SelectionSort;

import java.util.Arrays;

/**
 * 对数器的使用
 * （生成随机样本自己做比对的工具）
 *
 * 选择、冒泡、插入排序的对数器验证
 *
 * @author by jiweidong on 2021/11/20.
 */
public class Arg04_ResultValidatorUse {

    public static void main(String[] args) {

        int maxLen = 5;
        int maxValue = 10;
        int testTimes = 10000;
        for (int i = 0; i < testTimes; i++) {
            int[] oriArr = lenRandomValueRandom(maxLen, maxValue);

            int[] arr1 = copyArray(oriArr);
            SelectionSort.selectionSort(arr1);
            printErr("选择排序", oriArr, arr1);

            int[] arr2 = copyArray(oriArr);
            BubbleSort.bubbleSort(arr2);
            printErr("冒泡排序", oriArr, arr2);

            int[] arr3 = copyArray(oriArr);
            InsertionSort.insertionSort2(arr3);
            printErr("插入排序", oriArr, arr3);
        }
    }

    public static void printErr(String name, int[] orgArr, int[] sortedArr) {
        if (!isSorted(sortedArr)) {
            System.out.println(name + "错了！");
            System.out.println("原序列：" + Arrays.toString(orgArr));
            System.out.println("排序后：" + Arrays.toString(sortedArr));
        }
    }

    public static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
        }
        return arr;
    }

    // 返回一个数组arr，arr长度随机[0, maxLen-1]，arr中的每个值随机[0, maxValue-1]
    public static int[] lenRandomValueRandom(int maxLen, int maxValue) {
        int arrLen = (int) (Math.random() * maxLen) + 1;

        int[] arr = new int[arrLen];
        for (int i = 0; i < arrLen; i++) {
            arr[i] = (int) (Math.random() * maxValue) + 1;
        }

        return arr;
    }

    public static int[] copyArray(int[] arr) {
        int[] newArr = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            newArr[i] = arr[i];
        }
        return newArr;
    }

    // arr1和arr2一定等长
    public static boolean equalValues(int[] arr1, int[] arr2) {
        for (int i = 0; i < arr1.length; i++) {
            if (arr1[i] != arr2[i]) {
                return false;
            }
        }
        return true;
    }

    public static boolean isSorted(int[] arr) {
        if (arr.length < 2) {
            return true;
        }

        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (max > arr[i]) {
                return false;
            }
            max = arr[i];
        }

        return true;
    }
}
